package net.oschina.arvin.admin.web.controller;

import net.oschina.arvin.admin.model.Privilege;
import net.oschina.arvin.admin.model.vo.PrivilegeVO;
import net.oschina.arvin.admin.service.PrivilegeService;
import net.oschina.arvin.admin.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Arvin
 * @time 2017/11/25 21:35
 */
@Controller
@RequestMapping("/admin")
public class AdminIndexController {
    @Autowired
    private PrivilegeService privilegeService;

    @RequestMapping("/index.do")
    public String index(ModelMap modelMap) {

        modelMap.addAttribute("menus", JsonUtil.toJson(getTopLevelPrivilegeList()));

        return "admin/index";
    }

    /**
     * 获取顶级权限列表
     * @return
     */
    private List<PrivilegeVO> getTopLevelPrivilegeList() {
        List<Privilege> privilegeList = privilegeService.findAll();
        List<PrivilegeVO> topLevelPrivilegeList = new ArrayList<>();

        Map<Long, PrivilegeVO> privilegeVOMap = new HashMap<>();
        List<PrivilegeVO> allVoList = new ArrayList<>();
        Map<Long, List<PrivilegeVO>> childrenMap = new HashMap<>();

        for (Privilege privilege : privilegeList) {

            PrivilegeVO privilegeVO = new PrivilegeVO(privilege);
            privilegeVOMap.put(privilegeVO.getId(), privilegeVO);
            allVoList.add(privilegeVO);

            if (privilege.getParentId() == null || privilege.getParentId() < 1) {
                topLevelPrivilegeList.add(privilegeVO);
            } else {
                List<PrivilegeVO> children = childrenMap.get(privilege.getParentId());
                if (null == children) {
                    children = new ArrayList<>();
                    childrenMap.put(privilege.getParentId(), children);
                }
                children.add(privilegeVO);
            }
        }

        // 处理父子关系
        for (PrivilegeVO privilegeVO : allVoList) {
            Long parentId = privilegeVO.getParent() != null ? privilegeVO.getParent().getId() : null;
            if (null != parentId) {
                privilegeVO.setParent(privilegeVOMap.get(parentId));
            }
            privilegeVO.setParent(null);
            privilegeVO.setChildren(childrenMap.get(privilegeVO.getId()));
        }

        return topLevelPrivilegeList;
    }

}
